const express = require("express");
const multer = require("multer");
// const bodyParser = require('body-parser')
// const http = require("http")

const path = require("path");
const { jwts } = require("./utils/JsonWebtoken.js");
const EPSTATE = require("./config/state.json");
const config = require("./config/config.js");

const app = express();

// 跨域请求设置
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    // 这里加上"Access-Control-Expose-Headers", "Authorization"前端才能读取token
    res.header("Access-Control-Expose-Headers", "Authorization");
    if (req.method == "OPTIONS") res.sendStatus(200);
    else next();
});

// json设置
app.use(express.json());

// 全局token验证
app.all("*", async (req, res, next) => {
    // upload token验证
    let token = req.headers.authorization;
    if (token && req.path.indexOf("/upload") > -1) {
        token = token.substring(0, token.indexOf(",")); // 为什么又有个点儿？
        let user_id = jwts.verifyToken(token);

        if (user_id === null || user_id === undefined) {
            res.send({
                msg: "请先登录",
            });
            return;
        } else {
            next();
        }
    } else {
        next();
    }
});

// 静态资源
// 将静态资源放在全局验证之后
app.use(express.static(path.join(__dirname, "public")));

// var server = http.createServer(app);
// app.set('trust proxy', true);// 设置以后，req.ips是ip数组；如果未经过代理，则为[]. 若不设置，则req.ips恒为[]

// app.get('/ip', function(req, res){
//   console.log("headers = " + JSON.stringify(req.headers));// 包含了各种header，包括x-forwarded-for(如果被代理过的话)
//   console.log("x-forwarded-for = " + req.header('x-forwarded-for'));// 各阶段ip的CSV, 最左侧的是原始ip
//   console.log("ips = " + JSON.stringify(req.ips));// 相当于(req.header('x-forwarded-for') || '').split(',')
//   console.log("remoteAddress = " + req.connection.remoteAddress);// 未发生代理时，请求的ip
//   console.log("ip = " + req.ip);// 同req.connection.remoteAddress, 但是格式要好一些
//   res.send('Hello World');
// });

// 根目录
app.get("/", (req, res) => {
    res.send("Welcome to Experimental Process!");
});

// 路由
app.use("/login", require("./routes/Login.js"));
app.use("/blog", require("./routes/Blog.js"));
app.use("/blog_category", require("./routes/BlogCategory.js"));
app.use("/upload", require("./routes/UploadFiles.js"));
app.use("/register", require("./routes/Register.js"));
app.use("/files", require("./routes/OperateFile.js"));

// 捕获错误
app.use(function (err, req, res, next) {
    // console.warn('错误处理中间捕获Exception', err);
    // multer 会将错误传递给express
    if (err instanceof multer.MulterError) {
        // instanceof 用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
    } else if (err.name === "UnauthorizedError") {
        console.warn("无效的token", err);
    } else if (err) {
        console.warn("错误处理中间捕获Exception", err);
    }
    next();
});

// 监听器
app.listen(config.port, () => {
    console.log(`server startup on http://localhost:${config.port}`);
});
